package base

import (
	"context"
	"fmt"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	basePb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
	msgService "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/base/msg"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
)

type baseMsgServer struct {
	msgService msgService.MsgServiceIface
}

func NewBaseMsgServer(msgService msgService.MsgServiceIface) basePb.BaseMsgServiceServer {
	return &baseMsgServer{
		msgService: msgService,
	}
}

//
//// MsgSave 创建或更新
//func (s *baseMsgServer) MsgSave(ctx context.Context, req *basePb.MsgSaveRequest) (*basePb.MsgSaveResponse, error) {
//	var response = &basePb.MsgSaveResponse{}
//	if req.Param == nil {
//		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "参数为空")
//	}
//
//	if req.Param.MsgName == "" {
//		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "部门名称为空")
//	}
//
//	//if req.Param.ParentId == 0 {
//	//	return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "父级部门编号为空")
//	//}
//
//	msgObj := &msgRepo.GfyMsganizationPo{
//		Id:         req.GetParam().GetId(),
//		Name:       req.GetParam().GetMsgName(),
//		ParentId:   req.GetParam().ParentId,
//		Sort:       0,
//		CreatedOn:  time.Now(),
//		CreatedBy:  "",
//		ModifiedOn: time.Now(),
//		ModifiedBy: "",
//	}
//
//	msgId, err := s.msgService.Save(ctx, msgObj, req.GetParam().AreaCodes)
//	if err != nil {
//		stark.Logger.Infof(ctx, "MsgSave-error: %+v, msgObj: %+v", err, msgObj)
//		return response, errcode.CTogRPCError(err)
//	}
//
//	response.Id = msgId
//
//	return response, nil
//}
//
//// MsgDelete 删除消息
//func (s *baseMsgServer) MsgDelete(ctx context.Context, req *basePb.MsgDeleteRequest) (*basePb.MsgDeleteResponse, error) {
//	response := &basePb.MsgDeleteResponse{}
//	if req.MsgId == 0 {
//		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "部门编号为空")
//	}
//
//	err := s.msgService.Delete(ctx, req.MsgId)
//	if err != nil {
//		stark.Logger.Infof(ctx, "MsgDelete-error: %+v, msg_id: %d", err, req.MsgId)
//		return response, errcode.CTogRPCError(err)
//	}
//
//	response.Id = req.MsgId
//	return response, nil
//}

func (s *baseMsgServer) MsgSetReaded(ctx context.Context, request *basePb.MsgSetReadedRequest) (*basePb.MsgSetReadedResponse, error) {
	response := &basePb.MsgSetReadedResponse{}
	if request.Id <= 0 {
		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "id为空")
	}
	id, err := s.msgService.SetReaded(ctx, request)
	response.Id = id
	return response, err
}

// MsgList 消息列表
func (s *baseMsgServer) MsgList(ctx context.Context, req *basePb.MsgListRequest) (*basePb.MsgListResponse, error) {
	response := &basePb.MsgListResponse{}
	response.List = make([]*basePb.MsgItem, 0)
	list, pageInfo, err := s.msgService.List(ctx, req)
	if err != nil {
		stark.Logger.Infof(ctx, "MsgList-error: %+v", err)
		return response, errcode.CTogRPCError(err)
	}

	for _, item := range list {
		beCopyItem := &basePb.MsgItem{
			Id:           item.Id,
			MessageType:  item.MessageType,
			Title:        item.Title,
			Content:      item.Content,
			SenderId:     fmt.Sprintf("%d", item.SenderId),
			ReceiverId:   fmt.Sprintf("%d", item.ReceiverId),
			IsReaded:     int32(item.IsReaded),
			ReceivedTime: utils.TimeToString(item.ReceivedTime),
			ReadedTime:   utils.TimeToString(item.ReadedTime.Time),
			Link:         item.Link,
			CreatedBy:    item.CreatedBy,
			CreatedOn:    utils.TimeToString(item.CreatedOn),
			ModifiedBy:   item.ModifiedBy,
			ModifiedOn:   utils.TimeToString(item.ModifiedOn),
		}
		response.List = append(response.List, beCopyItem)
	}

	var readedTotal int64
	var unreadedTotal int64
	var allTotal int64
	if req.IsReaded == 0 {
		// 无状态，所有
		allTotal = pageInfo.Total
		unreadedTotal, err = s.msgService.GetReadStatusGroupSummary(ctx, 2)
		readedTotal = allTotal - unreadedTotal
	} else if req.IsReaded == 1 {
		// 已读
		readedTotal = pageInfo.Total
		unreadedTotal, err = s.msgService.GetReadStatusGroupSummary(ctx, 2)
		allTotal = unreadedTotal + readedTotal
	} else if req.IsReaded == 2 {
		// 未读
		unreadedTotal = pageInfo.Total
		readedTotal, err = s.msgService.GetReadStatusGroupSummary(ctx, 1)
		allTotal = unreadedTotal + readedTotal
	}
	if err != nil {
		return response, errcode.CTogRPCError(err)
	}

	response.Page = &basePb.BasePage{
		Page:     int32(pageInfo.Page),
		PageSize: int32(pageInfo.PageSize),
		Total:    int32(pageInfo.Total),
	}
	response.GroupSummary = &basePb.MsgListGroupSummary{
		ReadedTotal:   readedTotal,
		UnreadedTotal: unreadedTotal,
		AllTotal:      allTotal,
	}
	return response, nil
}

func (s *baseMsgServer) PushSiteMessage(ctx context.Context, req *basePb.SiteMessageRequest) (*basePb.SiteMessageResponse, error) {
	resp := &basePb.SiteMessageResponse{}

	//参数校验
	if req.Title == "" {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "title为空")
	}
	if req.Content == "" {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "content为空")
	}
	if req.ReceiverId == 0 {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "receiver_id为空")
	}
	if req.TenantCode == "" {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "tenant_code为空")
	}
	////如果context中没有tenant_code，tenant_code不能为空
	//tenantCode := authorize.GetTenantCode(ctx)
	//if tenantCode == "" {
	//	if req.TenantCode == "" {
	//		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "tenant_code为空")
	//	}
	//	ctx = context.WithValue(ctx, authorize.TENANT_CODE_KEY, req.TenantCode)
	//}
	tenantCode, err := tenant_db.GetTenantCode(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "tenant_code获取失败, error:%+v", err)
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "tenant_code获取失败")
	}
	if tenantCode != req.TenantCode {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "tenant_code与推送数据不一致")
	}

	err = s.msgService.PushSiteMsg(ctx, req)
	if err != nil {
		resp.IsSuccess = false
		return resp, errcode.CTogRPCError(err)
	}
	resp.IsSuccess = true
	return resp, nil
}

func (s *baseMsgServer) BatchPushSiteMessage(ctx context.Context, req *basePb.BatchSiteMessageRequest) (*basePb.SiteMessageResponse, error) {
	resp := &basePb.SiteMessageResponse{}
	if len(req.List) == 0 {
		return resp, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "数据为空")
	}

	err := s.msgService.BatchPushSiteMsg(ctx, req)
	if err != nil {
		resp.IsSuccess = false
		return resp, errcode.CTogRPCError(err)
	}
	resp.IsSuccess = true
	return resp, nil
}

//
//// ImportMsgs 消息列表
//func (s *baseMsgServer) ImportMsgs(ctx context.Context, req *basePb.ImportMsgRequest) (*basePb.ImportMsgResponse, error) {
//	response := &basePb.ImportMsgResponse{}
//	if (req.MsgDataList == nil) || len(req.MsgDataList) == 0 {
//		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "参数为空")
//	}
//
//	//s.msgService.ImportMsgs()
//
//	return response, nil
//}
